package behavioralPattern.strategy.example03;

import behavioralPattern.strategy.example02.Receipt;
import org.dom4j.Document;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.util.HashMap;
import java.util.Map;

/**
 * 策略工厂类
 * 创建具体策略类
 */
public class StrategyFactory {

    public StrategyFactory() {
    }

    // 使用map集合存储策略信息,彻底消除if else
    private static Map<String, ReceiptHandlerStrategy> map;

    // 初始化策略池
    public static void init(){
        map = new HashMap<>();
//        map.put("MT1101",new MT1101_Receipt());
//        map.put("MT2101",new MT2101_Receipt());
        SAXReader saxReader = new SAXReader();
        String file = "E:\\WorkSpace\\MyStudy\\MyProject\\allwe.day82_DesignPattern\\src\\main\\resources\\config.xml";
        try {
            Document document = saxReader.read(file);
            Node node = document.selectSingleNode("/confing/className");
            String className = node.getText();
            Class<?> clazz = Class.forName(className);
            ReceiptHandlerStrategy MT1101 = (ReceiptHandlerStrategy) clazz.newInstance();
            map.put(node.getName(),MT1101);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // 根据回执类型，获取对应策略对象
    public static ReceiptHandlerStrategy getStrategy(Receipt receipt){
        return map.get(receipt.getType());
    }
}
